﻿using System;
using System.Collections.Generic;
using EmbeddedSharp.Core;
using EmbeddedSharp.Scripting.Function;

namespace EmbeddedSharp.Scripting {
    public class ShellUtils {

        #region type checking routines
        public static bool IsOfType(object obj, Type type) {
            return obj.GetType().Equals(type);
        }

        public static bool IsSubclassOfType(object obj, Type type) {
            return obj.GetType().IsSubclassOf(type);
        }

        public static bool IsImplementedFromType(object obj, Type type) {
            Type[] ifx = obj.GetType().GetInterfaces();
            foreach (Type t in ifx) {
                if (t == type) {
                    return true;
                }
            }

            return false;
        }
        #endregion

        public static bool IsNumber(string value) {
            int dot = 0;

            foreach (char c in value) {
                if (c == '.') {
                    if (dot == 1) {
                        return false;
                    } else {
                        dot = 1;
                    }
                }
                else if (!char.IsDigit(c)) {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="node"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string InitUDF(
            UserDefinedFunctionNode node, string[] args)
        {
            List<string> argList = new List<string>(args);
            argList.Reverse();
            args = argList.ToArray();

            UserDefinedFunctionNode udf
                = node as UserDefinedFunctionNode;
            string expr = udf.FuncBody;

            for (int index = udf.Arguments.Length - 1;
                index >= 0; index--)
            {
                expr = Utils.ReplaceString(
                    udf.Arguments[index],
                    args[index], expr,
                    ReplacingMode.CompleteMatch
                    );
            }

            return expr;
        }

    }
}
